<template>
  <BasicModal v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, unref } from 'vue';
  import { modalFormSchema } from './data';
  import mcApi from 'mc-c2b2m-operator-api';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useUserStore } from '@/store/modules/user';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { AppAuthMethodModel } from 'mc-c2b2m-operator-api/types/sys';

  const { SysModule, SystemModule } = mcApi;
  const { OrgApi } = SystemModule;
  const { UserApi } = SysModule;

  const userStore = useUserStore();
  const { orgId } = userStore.getUserInfo;

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: modalFormSchema,
    baseColProps: { span: 22 },
    showActionButtonGroup: false,
  });

  const ifUpdate = ref<boolean>(false);
  const authMethodId = ref<string>('');
  const [registerModal, { setModalProps }] = useModalInner(async (data: any) => {
    await resetFields();
    ifUpdate.value = !!data.ifUpdate;
    setModalProps({
      // width: 555,
      minHeight: 50,
      confirmLoading: false,
      title: `${ifUpdate.value ? '编辑' : '新增'}员工`,
    });
    if (unref(ifUpdate)) {
      await setFieldsValue(data.record);
    }
    // 获取认证方式id
    UserApi.getAppAuthMethodList().then((res: AppAuthMethodModel[]) => {
      authMethodId.value = res?.[0]?.authMethodId;
    });
  });

  const { createMessage } = useMessage();
  const emits = defineEmits(['success']);
  async function handleOk() {
    try {
      if (!authMethodId.value) {
        createMessage.error('获取认证方式id失败！');
        return;
      }
      const values: any = await validate();
      setModalProps({ confirmLoading: true });
      const { account } = values;
      // 先创建账户
      const accountRes = await OrgApi.createAccount({
        value: account,
        authMethodId: authMethodId.value,
      });
      values.operatorId = accountRes.id;
      values.orgId = orgId;
      // 根据新账号添加组织成员
      await OrgApi.applyMemberToOrg(values);
      createMessage.success(`${unref(ifUpdate) ? '编辑' : '新增'}成功！`);
      emits('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style scoped lang="less"></style>
